package com.fyzk.activity.setting;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.app.TestActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.dialog.SharePop;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.HandlerTypeUtils;
import com.fyzk.utils.ScreenUtils;
import com.fyzk.utils.Utils;
import com.fyzk.utils.update.UpdateManager;
import com.fyzk.utils.update.VersionModel;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.BuildConfig;
import com.tyjc.lottery.R;

import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;


@ContentView(R.layout.ac_set)
public class SettingActivity extends BaseActivity {
    private Context context = this;
    private TopTitleView help_top_rl;

    private RelativeLayout gengxin;
    private TextView help;
    // private TextView yindao;
    private TextView fenXiang;//分享
    private TextView fankui;
    private TextView about;
    private RelativeLayout update;
    private TextView feedBack;//意见反馈

    private TextView logout;
    private Button makecrash;

    private HelpClick helpClick;
    private TextView tv_update;
    private TextView tv_phone;
    //客服电话
    private String servicePhone = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        servicePhone = MySharedPreferences.getInstance().getServicePhone();
        info();
    }

    @Override
    public void onBackPressed() {
        // MainGroupActivity.exitTiShi(this);
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (!MySharedPreferences.getInstance().getLoginStatus()) {
            logout.setVisibility(View.INVISIBLE);
        } else {
            logout.setOnClickListener(helpClick);
        }
    }

    private void info() {
        if (null == helpClick) {
            helpClick = new HelpClick();
        }
        //根据路径得到Typeface
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/pingfang.ttf");
        help_top_rl = (TopTitleView) findViewById(R.id.help_top_rl);

        gengxin = (RelativeLayout) findViewById(R.id.help_gengxin);
        help = (TextView) findViewById(R.id.help_help);
        help.setTypeface(tf);
        // yindao = (TextView) findViewById(R.id.help_yindao);
        fenXiang = (TextView) findViewById(R.id.help_fenxiang);
        fenXiang.setTypeface(tf);
        fankui = (TextView) findViewById(R.id.help_fankui);
        fankui.setTypeface(tf);
        update = (RelativeLayout) findViewById(R.id.help_servicephone);
        about = (TextView) findViewById(R.id.help_about);
        about.setTypeface(tf);
        feedBack=(TextView) findViewById(R.id.feedback);
        feedBack.setTypeface(tf);
        logout = (TextView) findViewById(R.id.help_logout);
        logout.setTypeface(tf);
        makecrash = (Button) findViewById(R.id.makecrash);
        tv_update = (TextView) findViewById(R.id.tv_update);
        tv_update.setTypeface(tf);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_phone.setTypeface(tf);
        String curVersion = AppUtil.getCurrentVersion(context);
        tv_update.setText("（当前版本：" + curVersion + "）");

//        tv_phone.setText(servicePhone);

        // 事件
        gengxin.setOnClickListener(helpClick);
        help.setOnClickListener(helpClick);
        update.setOnClickListener(helpClick);
        // yindao.setOnClickListener(helpClick);
        fenXiang.setOnClickListener(helpClick);
        fankui.setOnClickListener(helpClick);
        makecrash.setOnClickListener(helpClick);
        about.setOnClickListener(helpClick);
        help_top_rl.setOnTitleClickListener(this);
    }

    class HelpClick implements OnClickListener {

        @Override
        public void onClick(View v) {

            Intent intent = null;

            switch (v.getId()) {
                case R.id.help_gengxin:
                    // 版本检测方式2：带更新回调监听
                    String url = UrlDef.UPDATE_URL + BuildConfig.UPDATE_KEY;
                    JSONObject request_json = new JSONObject();
                    try {
                        httpPostJsonNo(CommandUtil.UPDATE, "", request_json,
                                false, url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.help_help:
                    intent = new Intent(SettingActivity.this, Helps.class);
                    startActivity(intent);
                    break;
                case R.id.help_fenxiang:
                    toFenXiang();
                    break;
                case R.id.help_fankui:
                    intent = new Intent(SettingActivity.this, FeedbackActivity.class);
                    startActivity(intent);
                    break;
                case R.id.help_about:
                    intent = new Intent(SettingActivity.this, AboutActivity.class);
                    startActivity(intent);
                    break;
                case R.id.makecrash://测试程序崩溃
                    intent = new Intent(SettingActivity.this, TestActivity.class);
                    startActivity(intent);
                    break;
                case R.id.help_logout:
                    new AlertDialog.Builder(SettingActivity.this).setMessage("确定退出登录?").setPositiveButton("确定", new DialogInterface.OnClickListener
                            () {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            actionLogout();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).setCancelable(false).create().show();

                    break;
                case R.id.help_servicephone:
                    call(servicePhone);
                    break;
            }

        }
    }


    public void actionLogout() {
        AppLotteryInfos.clear();
        ViewCallBack.getInstance().countDownObjs.clear();
//        ActivityTaskManager.getInstance().closeAllActivity();
        MySharedPreferences.getInstance().setLoginStatus(false);
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.UPDATE:
                VersionModel beans = JSON.parseObject(resultBean.getData(), VersionModel.class);
                UpdateManager.getUpdateManager().getVersion(this, beans, "1");

                if (beans != null) {

                    if (!TextUtils.isEmpty(beans.getQr_url())) {
                        MySharedPreferences.getInstance().setQrUrl(beans.getQr_url());
                    }

                    if (!TextUtils.isEmpty(beans.getHandsel_content())) {
                        MySharedPreferences.getInstance().setHandselContent(beans.getHandsel_content());
                    }

                    VersionModel.Version model = beans.getVersion();

                    if (model != null && !TextUtils.isEmpty(model.getCustomercalls())) {
                        MySharedPreferences.getInstance().setCustomerCalls(model.getCustomercalls());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getQQ())) {
                        MySharedPreferences.getInstance().setServiceQQ(model.getQQ());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getDrawContent())) {
                        MySharedPreferences.getInstance().setDrawContent(model.getDrawContent().replaceAll("\\\\n","\n"));
                    }

                    String splashImageUrl = MySharedPreferences.getInstance().getSplashImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !splashImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setSplashImageUrl(model.getImage_url());
                    }
                    //客服微信图片暂时用跟启动图一样的
                    String qqImageUrl = MySharedPreferences.getInstance().getQQImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !qqImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setQQImageUrl(model.getImage_url());
                    }
                }

                break;
        }

    }

    protected void onFailure(int requestCode, String message) {
        onFailure(requestCode, "", message);
        switch (requestCode) {
            case CommandUtil.UPDATE:
                Utils.showToast(getContext(), message, this);
                break;
        }
    }

    private void call(String phone) {
        PackageManager pm = getPackageManager();
        boolean telephony = pm
                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
        if (telephony) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            showToast("本设备不支持拨打电话");
        }
    }

    @Override
    protected void parserMessage(Message msg) {
        // TODO Auto-generated method stub
        super.parserMessage(msg);
        DJ_ProgressDialog.dissmiss();
        switch (msg.what) {
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_SUCCESS:
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_EMPTY:
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_FAIL:
                AppToast.getToast().show(msg.obj.toString());
                break;
        }
    }


    /**
     * 分享
     */
    private void toFenXiang() {
        int height = ScreenUtils.getInstance().getHeight();
        if (Build.VERSION.SDK_INT > 19) {
            height = height - AppUtil.dip2px(this, 25);
        }
        SharePop sharePop = new SharePop(this, ScreenUtils.getInstance().getWidth(), height);
        sharePop.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, 0);

    }

}
